package org.mall.modules.member.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.mall.common.api.vo.CommonResult;
import org.mall.common.api.vo.Result;
import org.mall.common.api.vo.SMSMQDTO;
import org.mall.common.aspect.annotation.AutoLog;
import org.mall.common.aspect.annotation.IPLimit;
import org.mall.common.constant.AppMessageTypeEnum;
import org.mall.common.system.query.QueryGenerator;
import org.mall.common.system.util.JwtUtil;
import org.mall.common.util.DateUtils;
import org.mall.common.util.ObjectUtils;
import org.mall.common.util.RedisUtil;
import org.mall.common.util.json.JacksonUtils;
import org.mall.common.util.oConvertUtils;
import org.mall.convert.system.AppMessageConvert;
import org.mall.modules.member.entity.Feedback;
import org.mall.modules.member.entity.Member;
import org.mall.modules.member.entity.MemberShopCollectionDO;
import org.mall.modules.member.entity.MemberVo;
import org.mall.modules.member.service.IMemberService;
import org.mall.modules.member.service.IMemberShopCollectionService;
import org.mall.modules.message.entity.AppMessage;
import org.mall.modules.message.service.AppMessageService;
import org.mall.modules.message.service.IAppMessageService;
import org.mall.modules.pojo.common.AppMessageDTO;
import org.mall.modules.pojo.message.AppMessageVO;
import org.mall.modules.pojo.shop.ShopDTO;
import org.mall.modules.promotion.service.CouponService;
import org.mall.modules.shop.service.ShopService;
import org.mall.modules.system.client.SmsClient;
import org.mall.modules.system.model.VerificationCode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @Description: 商城用户
 * @Author: jeecg-boot
 * @Date: 2019-10-18
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "商城用户")
@RestController
@RequestMapping("/member")
public class MemberController {
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IAppMessageService messageService;

    @Autowired
    private RedisUtil redisUtil;


   @Autowired
    private AppMessageService appMessageService;

   @Autowired
   private IMemberShopCollectionService shopCollectionService;

   @Autowired
   private ShopService shopService;
    @Autowired
    private SmsClient smsClient;

   @Autowired
   private CouponService couponService;



    /**
     * 分页列表查询
     *
     * @param member
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "商城用户-分页列表查询")
    @ApiOperation(value = "商城用户-分页列表查询", notes = "商城用户-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<Member>> queryPageList(Member member,
                                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                               HttpServletRequest req) {
        Result<IPage<Member>> result = new Result<IPage<Member>>();
        QueryWrapper<Member> queryWrapper = QueryGenerator.initQueryWrapper(member, req.getParameterMap());
        //增加判断条件，只查询未删除的
        queryWrapper.eq("is_delete",0);
        queryWrapper.eq("type",0);
        Page<Member> page = new Page<Member>(pageNo, pageSize);
        IPage<Member> pageList = memberService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     *
     * @param member
     * @return
     */
    @AutoLog(value = "商城用户-添加")
    @ApiOperation(value = "商城用户-添加", notes = "商城用户-添加")
    @PostMapping(value = "/add")
    public Result<Member> add(@RequestBody Member member) {
        Result<Member> result = new Result<Member>();
        Member m = memberService.getByMobile(member.getMobile());
        if(null != m){
            Member temp = new Member();
            temp.setId(m.getId());
            temp.setIsDelete(0);
            temp.setType(0);
            memberService.updateById(temp);
            result.success("添加成功！");
        }else {
            try {
                member.setType(0);
                memberService.save(member);
                result.success("添加成功！");
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                result.error500("操作失败");
            }
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param member
     * @return
     */
    @AutoLog(value = "商城用户-编辑")
    @ApiOperation(value = "商城用户-编辑", notes = "商城用户-编辑")
    @PutMapping(value = "/edit")
    public Result<Member> edit(@RequestBody Member member) {
        Result<Member> result = new Result<Member>();
        Member memberEntity = memberService.getById(member.getId());
        if (memberEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = memberService.updateById(member);
            //TODO 返回false说明什么？
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "商城用户-通过id删除")
    @ApiOperation(value = "商城用户-通过id删除", notes = "商城用户-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            memberService.deleteById(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "商城用户-批量删除")
    @ApiOperation(value = "商城用户-批量删除", notes = "商城用户-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<Member> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<Member> result = new Result<Member>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.memberService.deleteByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "商城用户-通过id查询")
    @ApiOperation(value = "商城用户-通过id查询", notes = "商城用户-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<Member> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<Member> result = new Result<Member>();
        Member member = memberService.getById(id);
        if (member == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(member);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
        // Step.1 组装查询条件
        QueryWrapper<Member> queryWrapper = null;
        try {
            String paramsStr = request.getParameter("paramsStr");
            if (oConvertUtils.isNotEmpty(paramsStr)) {
                String deString = URLDecoder.decode(paramsStr, "UTF-8");
                Member member = JSON.parseObject(deString, Member.class);
                queryWrapper = QueryGenerator.initQueryWrapper(member, request.getParameterMap());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<Member> pageList = memberService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "商城用户列表");
        mv.addObject(NormalExcelConstants.CLASS, Member.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("商城用户列表数据", "导出人:Jeecg", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<Member> listMembers = ExcelImportUtil.importExcel(file.getInputStream(), Member.class, params);
                memberService.saveBatch(listMembers);
                return Result.ok("文件导入成功！数据行数:" + listMembers.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException  e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

    @GetMapping("/app/getPersonalInfo")
    public Result<?> getPersonalInfo() {
        Member member = memberService.getById(JwtUtil.getUserInfoByToken().getUserId());
        if (member==null||member.getIsDelete()==1||member.getState()==1){
            return Result.error("用户不存在");
        }

        MemberVo memberVo = new MemberVo();

        BeanUtil.copyProperties(member, memberVo);
        memberVo.setCardNum(couponService.getCouponCardCount(JwtUtil.getUserIdByToken()));
        return Result.ok(memberVo);
    }

    @PostMapping("/app/updatePersonalInfo")
    public Result<?> updatePersonalInfo(@RequestBody MemberVo memberVo){
        Member member=new Member();
        BeanUtil.copyProperties(memberVo,member);
        member.setId(JwtUtil.getUserInfoByToken().getUserId());
        memberService.updateById(member);
        return Result.ok("修改成功");
    }
    @IPLimit(count = 1,time = 60)
    @GetMapping("/app/getVerificationCode")
    public Result<?> getVerificationCode(@RequestParam String mobile){

        Member member=memberService.getById(JwtUtil.getUserInfoByToken().getUserId());
        if (member==null||member.getState()==1||member.getIsDelete()==1){
            return Result.error("");
        }
        String code= RandomUtil.randomNumbers(4);
        for (;;){

            if (!code.startsWith("0")){
                break;
            }
            code=RandomUtil.randomNumbers(4);

        }
        redisUtil.setSellerCode(mobile,code,4000);
        VerificationCode code1=new VerificationCode();
        code1.setCode(code);
        SMSMQDTO smsmqdto=new SMSMQDTO();
        smsmqdto.setMobile(mobile);
        smsmqdto.setCode(code);
        smsClient.singleSendVerificationCode(mobile,code);
        return Result.ok(code1);
    }

    @PostMapping("/app/updateMobile")
    public Result<?> updateMobile(@RequestBody MemberVo memberVo){
        if (memberVo.getMobile()==null||memberVo.getCode()==null){
            return Result.error("");
        }
        //TODO 验证码逻辑

        Member member=new Member();
        member.setId(JwtUtil.getUserInfoByToken().getUserId());
        member.setMobile(memberVo.getMobile());
        memberService.updateById(member);

        //-------------消息通知---------------
        AppMessageDTO appMessageDTO = new AppMessageDTO();
        appMessageDTO.setTitle("更换手机号");
        appMessageDTO.setCreateTime(DateUtils.getDate());
        appMessageDTO.setContent("您于"+DateUtils.getDate()+"更换手机号码，变更后手机号码为："+memberVo.getMobile());
        appMessageDTO.setReceiver(memberVo.getMobile());
        appMessageDTO.setType(AppMessageTypeEnum.CHANGE_PASSWORD_MOBILE.getValue());
        appMessageService.sendAppMessageToUser(appMessageDTO);

        return Result.ok();
    }

    @GetMapping("/app/getMessageList")
    public Result<?> getAppMessageList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize){


        String userId=JwtUtil.getUserIdByToken();
        Page page=new Page<>();
        page.setSize(pageSize).setCurrent(pageNo);

        IPage<AppMessage> temp =messageService.getPageListOfMessage(page,userId);
        page.setTotal(temp.getTotal());
        page.setRecords(temp.getRecords().stream().map(AppMessageConvert.INSTANCE::convert2).collect(Collectors.toList()));
        log.info(JacksonUtils.toJSONString(page));
        return Result.ok(page);


    }

    @GetMapping("/app/getNewMessageList")
    public Result getNewMessageList(@RequestParam Long id){
        List<AppMessage> appMessages=messageService.getNewMessageListById(JwtUtil.getUserIdByToken(),id);
        return Result.ok(ObjectUtils.copyList(appMessages,AppMessageVO.class));
    }
    @PostMapping("/app/updateMessageStatus")
    public Result updateMessageStatus(@RequestBody AppMessageVO vo){

        AppMessage appMessage=new AppMessage();
        appMessage.setIsRead(vo.getIsRead());
        appMessage.setId(vo.getId());

        messageService.updateById(appMessage);

        return Result.ok();
    }

    @PostMapping("/app/modifyFeedBack")
    public Result modifyFeedBack(@RequestBody Feedback feedback){
        feedback.setUserId(JwtUtil.getUserIdByToken());
        feedback.setCreateTime(new Date());
        feedback.setUserName(JwtUtil.getUserNameByToken());
        if (memberService.modifyFeedBack(feedback)){
            return Result.ok();
        }
        return Result.ok();
    }
    @PostMapping("/app/favoriteShop")
    public Result favoriteShop(@RequestBody Map<String,Object> params){

        String shopId= (String) params.get("shopId");
        if (shopId==null){
            return Result.error("");
        }
        Integer hasCollectionType=(Integer) params.get("hasCollectionType");

        CommonResult<ShopDTO> commonResult= shopService.getOneShopInfoByShopId(shopId);
        if (commonResult.isSuccess()&&commonResult.getData()!=null){
            ShopDTO shopDTO=commonResult.getData();
            if (shopDTO.getIsDelete()==1||shopDTO.getIsDelete()==null){
                return Result.error("商店不存在");
            }
            if (hasCollectionType==2){
                if (!shopCollectionService.hasUserSpuFavorite(JwtUtil.getUserIdByToken(),shopId)){
                    return Result.error("用户为收藏该商店");
                }
                shopCollectionService.removeUserFavorite(JwtUtil.getUserIdByToken(),shopId);
            }else {
                if (shopCollectionService.hasUserSpuFavorite(JwtUtil.getUserIdByToken(),shopId)){
                    return Result.error("用户已收藏该商店");
                }
                MemberShopCollectionDO shopCollectionDO=new MemberShopCollectionDO();
                BeanUtils.copyProperties(shopDTO,shopCollectionDO);
                shopCollectionDO.setUserId(JwtUtil.getUserIdByToken());
                shopCollectionDO.setShopId(shopDTO.getId());
                shopCollectionService.save(shopCollectionDO);
            }

        }

        return Result.ok();

    }

}
